package eu.telecombretagne.rsm.base.entity;

import eu.telecombretagne.rsm.base.event.*;
import eu.telecombretagne.rsm.gui.NameConsts;
import eu.telecombretagne.rsm.gui.frames.DesktopFrame;
import eu.telecombretagne.rsm.protocol.ABP.util.Automata;
import eu.telecombretagne.rsm.protocol.ABP.util.AutomataState;

public class AltBitReceiverEntity extends Entity {

	static private Class<?> [] producedEvents = {AckEvent.class};
	static private Class<?> [] consumedEvents = {FrameEvent.class};
	private Automata automate;
	
	public AltBitReceiverEntity (EventChannel ec) {
		super (ec, producedEvents, consumedEvents);
		automate = new Automata(AutomataState.REPOS0, false);
	}
	
	public void run () {
		DesktopFrame.writeLogReceiver(NameConsts.ALTERNATINGBITRECEIVERISRUNNING);
		
		while(runSwitch){
			Event e = null;
			try {
				e = this.consume ();
			}
			catch (InterruptedException ie) {
				DesktopFrame.writeLogError(NameConsts.FATALERRORDURINGEVENTCONSUMPTION + ie);
				System.exit(0);
			}
			switch (automate.getState ()) {
			
			case REPOS0: 
				if (e.getClass () == FrameEvent.class) {
					FrameEvent me = (FrameEvent) e;
					if (me.getNum() == 0) {
						AppMessageEvent ame = new AppMessageEvent (me.getBody());
						produce (ame);
						produce (new AckEvent (0));
						automate.setState (AutomataState.REPOS1);
					}
					else produce (new AckEvent (1));
				}
				break;
			
			case REPOS1 :
				if (e.getClass () == FrameEvent.class) {
					FrameEvent me = (FrameEvent) e;
					if (me.getNum() == 1) {
						AppMessageEvent ame = new AppMessageEvent (me.getBody());
						produce (ame);
						produce (new AckEvent (1));
						automate.setState (AutomataState.REPOS0);
					}
					else produce (new AckEvent (0));
				}
				break;
			}
		}
	}
}